import { Component } from "@angular/core";
import { BusiProvider } from '../../providers/busi/busi';
import { Global } from '../../common/global';
import {
  IonicPage,
  NavController,
  NavParams,
  PopoverController
} from "ionic-angular";

/**
 * Generated class for the ProductPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: "page-product",
  templateUrl: "product.html"
})
export class ProductPage {
  //1 是普通商品 2 商家商品
  type: any = "1";
  productlist:any;
  productlistCopy:any;
  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    public popoverCtrl: PopoverController,
    public busi:BusiProvider
  ) {}

    ionViewDidEnter(){
      this.getProductList();
    }

  popover(myEvent) {
    let popover = this.popoverCtrl.create("PopoverPage", {
      callback: this.callback
    });
    popover.present({
      ev: myEvent
    });
  }

  callback = (type) => {
    return new Promise((resolve, reject) => {
      this.type = type;
      this.getProductList();
      resolve();
    });
  };

  getProductList(){
    this.busi.getProduct(this.type).subscribe(
      data=>{
        this.productlist = data.products;
        this.productlistCopy = data.products;
      },
      error=>{

      }
    );
  }
  productdetail(prodid){
    this.navCtrl.push("ProductdetailPage",{prodid:prodid});
  }
  getImageUrl(url ){
    return Global.base_url + url;
  }

  search(env){
    var val = env.target.value;

    // if the value is an empty string don't filter the items
    if (val && val.trim() != '') {
      this.productlistCopy = this.productlist.filter((item) => {
        return (item.title.indexOf(val) > -1 || item.desc.indexOf(val) > -1);
      })
    }else{
      this.productlistCopy = this.productlist;
    }
  }
}
